import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
# 邮箱配置
smtp_server = "smtp.163.com"
smtp_port = 465  # SSL 端口
sender_email = "yuchuangcn@163.com"   # 发件人你的163邮箱
auth_code = "CQhf837hqLmrqxxG"             # 注意：不是邮箱密码，而是开启SMTP时的授权码
receiver_email = "yuchuangcn@163.com"  # 收件人



def send_mail_bond_value (content,receive_email):
    title="转债价格小于纯债价值"
    __send_163_email(title,content,receive_email)
 
def send_mail_ytm_rt (content,receive_email):
    title="转债收益率大于8%"
    __send_163_email(title,content,receive_email)




def __send_163_email(subject,content,receive_email) :
    if receive_email is None :
        receive_email=receiver_email

    # 使用 MIMEMultipart，可以支持附件
    message = MIMEMultipart()
    message["From"] = Header(f"投资服务 <{sender_email}>", "utf-8")

    message["To"] = formataddr((str(Header("投资服务", "utf-8")), receive_email))
    message["Subject"] = Header(subject, "utf-8")

    # 添加邮件正文
    message.attach(MIMEText(content, "plain", "utf-8"))

    try:
        # 连接服务器并登录
        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server.login(sender_email, auth_code)

        # 发送邮件
        server.sendmail(sender_email, [receiver_email], message.as_string())
        print("✅ 邮件发送成功！")

        server.quit()
    except Exception as e:
        print("❌ 邮件发送失败:", str(e))
